package com.szjz.excel.importexport.util;

import com.szjz.excel.importexport.ExcelWriter;
import lombok.SneakyThrows;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.poi.ss.usermodel.Sheet;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.List;

/**
 * Excel工具类
 */
public class ExcelUtil {

    /**
     * excel 写入表格路径
     */
    public static final String EXCEL_WRITE_PATH = "src/main/resources/static/excel/write/writeExcel.xlsx";

    /**
     * excel 读取表格路径
     */
    public static final String EXCEL_READ_PATH = "src/main/resources/static/excel/read/readExcel.xlsx";


    /**
     * 是否为XLS格式的Excel文件（HSSF）<br>
     * XLS文件主要用于Excel 97~2003创建
     *
     * @param in excel输入流
     * @return 是否为XLS格式的Excel文件（HSSF）
     * @throws IOException
     */
    public static boolean isXls(InputStream in) throws IOException {
        final PushbackInputStream pin = (in instanceof PushbackInputStream) ? (PushbackInputStream) in
                : new PushbackInputStream(in, 8);
        return FileMagic.valueOf(pin) == FileMagic.OLE2;
    }

    /**
     * 是否为XLSX格式的Excel文件（XSSF）<br>
     * XLSX文件主要用于Excel 2007+创建
     *
     * @param in excel输入流
     * @return 是否为XLSX格式的Excel文件（XSSF）
     * @throws IOException
     */
    public static boolean isXlsx(InputStream in) throws IOException {
        if (false == in.markSupported()) {
            in = new BufferedInputStream(in);
        }
        return FileMagic.valueOf(in) == FileMagic.OOXML;
    }

    /**
     * sheet是否为空
     *
     * @param sheet {@link Sheet}
     * @return sheet是否为空
     * @since 4.0.1
     */
    public static boolean isEmpty(Sheet sheet) {
        return null == sheet || (sheet.getLastRowNum() == 0 && sheet.getPhysicalNumberOfRows() == 0);
    }

    @SneakyThrows
    public static void export(HttpServletResponse response, List exportList) {
        if (null == exportList || exportList.size() < 1) {
            throw new RuntimeException("暂无数据");
        }
        ExcelWriter writer = ExcelWriter.build(exportList.get(0).getClass(), ExcelUtil.EXCEL_WRITE_PATH, null);
        writer.write(exportList);
        writer.getResponseEntity(response);
        writer.close();
    }


}
